package io.kiki.stack.http.feign.form.multipart;

import feign.RequestTemplate;
import feign.codec.EncodeException;
import feign.codec.Encoder;
import lombok.RequiredArgsConstructor;
import lombok.experimental.FieldDefaults;
import lombok.val;

import static lombok.AccessLevel.PRIVATE;

/**
 * A delegate writer.
 *
 * @author Artem Labazin
 */
@RequiredArgsConstructor
@FieldDefaults(level = PRIVATE, makeFinal = true)
public class DelegateWriter extends AbstractWriter {

    Encoder delegate;

    SingleParameterWriter parameterWriter = new SingleParameterWriter();

    @Override
    public boolean isApplicable(Object value) {
        return true;
    }

    @Override
    protected void write(Output output, String key, Object value) throws EncodeException {
        val fake = new RequestTemplate();
        delegate.encode(value, value.getClass(), fake);
        val bytes = fake.body();
        val string = new String(bytes, output.getCharset()).replaceAll("\n", "");
        parameterWriter.write(output, key, string);
    }
}
